<?php
use think\Db;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting(E_ERROR | E_PARSE );

/**
 * 上传文件
 * @Author   CCH
 * @DateTime 2020-05-23T12:20:41+0800
 * @param    file   file文件对象
 * @return   上传结果
 */
function uploadFile($file_name,$tmp_name,$path='',$is_use_name=false){
    try{
        $config = config('config.aliyun_oss');
        $object = !$is_use_name ? $path.uuidCreate().'.'.pathinfo($file_name,PATHINFO_EXTENSION) : $path.$file_name;
        $oss = new \OSS\OssClient($config['keyId'],$config['keySecret'],$config['endpoint']);
        $result = $oss->uploadFile($config['bucket'], $object, $tmp_name);
        return ['status'=>1,'data'=>$object];
    } catch(OssException $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }
    return true;
}

function validsHtml($valids){
    $contents = [];
    foreach ($valids as $valid) {
        if ($valid == 'required') {
            $contents[] = '<span class="text-danger">*</span>';
        }
    }
    echo implode('',$contents);
}

function timeDef($val, $default = "", $format = 'Y-m-d H:i'){
    return empty($val) ? $default : date($format,$val);
}
// 格式化日期
function timeFormat($val,$format = 'Y-m-d H:i'){
    if (empty($val)) {
        return '';
    }
    return date($format,strtotime($val));
}

function actionCn($key){
	$list = [
		'index'=>'列表',
		'add'=>'新增',
		'edit'=>'编辑',
		'view'=>'详情',
		'delete'=>'删除'
	];
	return $list[$key];
}

// url默认空链接
function urlDef($url){
	return empty($url) ? 'javascript:void(0)' : $url;
}

// 将数组参数提取出来
function arrayParamExtract($list,$key,$val){
    $result = [];
    foreach ($list as $k => $vo) {
        $result[$vo[$key]] = $vo[$val];
    }
    return $result;
}

// 将数组参数提取出来
function arrayParamExtractVal($list){
    $result = [];
    foreach ($list as $k => $vo) {
        $result[$vo] = $vo;
    }
    return $result;
}

// 生成 增/改 页面校验
function createPageValid($fields=[]){
	$rules = [];
    $messages = [];
    foreach ($fields as $field => $vo) {
        if (!empty($vo['valids'])) {
            $rule = [];
            $message = [];
            foreach ($vo['valids'] as $valid) {
                $rule[$valid] = true;
                $message[$valid] = '请输入'.$vo['name'];
            }
            $rules[$field] = $rule;
            $messages[$field] = $message;
        }
    }
    if (empty($rules)) {
		return [];
	}
	return ['rules'=>$rules,'messages'=>$messages];
}

// 空默认
function emptyDef($val, $default="", $type='empty') {
    switch ($type) {
        case 'empty':
            return empty($val) ? $default : $val;
            break;
        case 'isset':
            return isset($val) ? $val : $default;
            break;
        default:
            return empty($val) ? $default : $val;
            break;
    }
}

/**
 * 创建多个重复字符拼接字符串
 * @Author   CCH
 * @DateTime 2020-08-15T23:05:10+0800
 * @param    $str  重复字符
 * @param    $num  重复次数
 * @param    $join 拼接符号
 * @return   拼接后字符串
 */
function stringRange($str,$num=1,$join=''){
    $result = [];
    for ($i=0; $i < $num; $i++) { 
        $result[] = $str;
    }
    return implode($join, $result);
}

// 随机颜色
// function randomColor(){
//     mt_srand((double)microtime()*1000000);
//     $c = '';
//     while(strlen($c)<6){
//         $c .= sprintf("%02X", mt_rand(0, 255));
//     }
//     return $c;
// }

// 判断是否加入筛选
function getSearchParam($params,$prefix=''){
    $map = [];
    foreach ($params as $key => $param) {
        if ( isSearchParam($param['key']) ) {
            switch ($param['type']) {
                case '=': 
                    $map[] = [$prefix.$param['key'],'=',input($param['key'])];
                    break;
                case '>': 
                    $map[] = [$prefix.$param['key'],'>',input($param['key'])];
                    break;
                case '>=': 
                    $map[] = [$prefix.$param['key'],'>=',input($param['key'])];
                    break;
                case '<': 
                    $map[] = [$prefix.$param['key'],'<',input($param['key'])];
                    break;
                case '<=': 
                    $map[] = [$prefix.$param['key'],'<=',input($param['key'])];
                    break;
                case 'like': 
                    $map[] = [$prefix.$param['key'],'like','%'.input($param['key']).'%'];
                    break;
                default: break;
            }
        }
    }
    return $map;
}

function isSearchParam($param){
    return input($param,null) != null;
}

// 是否下拉选中
function isSelected($val1, $val2, $res = "selected") {
    if (!isset($val1) || !isset($val2)) {
        return "";
    }
    return (string)$val1==(string)$val2?$res:"";
} 

function delEmpty($data){
    foreach ($data as $k => $vo) {
        if (empty($vo) && $vo != '0') {
            unset($data[$k]);
        }
    }
    return $data;
}

// 参数过滤（筛选）
function paramFilter($params,$fields=[],$cns=[]){
    $result = [];
    foreach ($fields['must'] as $k => $field) {
        if (empty($params[$field]) && $params[$field] != '0') {
            $txt = empty($cns[$field]) ? $field : $cns[$field];
            return ['error_msg'=>'参数不能为空('.$txt.')'];
        }
        $result[$field] = $params[$field];
    }
    // foreach ($fields['onemust'] as $k => $field_list) {
    //     $is_exist = false;
    //     foreach ($field_list as $field) {
    //         if ( !empty($params[$field]) ) {
    //             $result[$field] = $params[$field];
    //             $is_exist = true;
    //             break;
    //         }
    //     }
    //     if (!$is_exist) {
    //         return ['error_msg'=>'参数不能为空('.implode(' | ', $field_list).')'];
    //     }
    // }
    foreach ($fields['nomust'] as $k => $field) {
        isset($params[$field]) && $result[$field] = $params[$field];
    }
    return $result;
}

// textarea正常显示
function myTextareaShow($content){
    // return str_replace(" ","&nbsp;",str_replace("\n","<br/>",$content)); 
    return str_replace("\n","<br/>",$content); 
}

/**
 * 生成UUID
 * @Author   CCH
 * @DateTime 2020-05-23T11:59:13+0800
 * @return   UUID
 */
function uuidCreate() {
    if (function_exists('com_create_guid')){
       $uuid = com_create_guid();
    }else{
       mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
       // $charid = strtoupper(md5(uniqid(rand(), true)));
       $charid = md5(uniqid(rand(), true));
       $hyphen = chr(45);
       $uuid = chr(123)
               .substr($charid, 0, 8).$hyphen
               .substr($charid, 8, 4).$hyphen
               .substr($charid,12, 4).$hyphen
               .substr($charid,16, 4).$hyphen
               .substr($charid,20,12)
               .chr(125);
    }
    $uuid = str_replace(array('{','}','-'), '', $uuid);
    return strtoupper($uuid);
} 

/**
 * 检验数据的真实性，并且获取解密后的明文.
 * @param $encrypted_data string 加密的用户数据
 * @param $iv string 与用户数据一同返回的初始向量
 * @param $data string 解密后的原文
 *
 * @return int 成功0，失败返回对应的错误码
 */
function xcxDecryptData($session_key,$encrypted_data,$iv)
{
    if (strlen($session_key) != 24) {
        return ['status'=>0,'msg'=>'错误sessionKey'];
    }
    $aesKey=base64_decode($session_key);
    if (strlen($iv) != 24) {
      return ['status'=>0,'msg'=>'错误iv'];
    }
    $aesIV=base64_decode($iv);
    $aesCipher=base64_decode($encrypted_data);
    $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
    $data = json_decode($result,true);
    if (empty($data)) {
      return ['status'=>0,'msg'=>'解密失败'];
    }
    return ['status'=>1,'data'=>$data];
}

function myExplode($str, $separator = ',')
{
    if (!empty($str)) {
        return explode($separator, $str);
    }
    return $str;
}

/**
 *  @desc 根据两点间的经纬度计算距离
 *  @param float $lat 纬度值
 *  @param float $lng 经度值
 */
function getDistance($lat1, $lng1, $lat2, $lng2) {
    $earthRadius = 6371000;
    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;

    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;

    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}

/**
 * 二位数组根据某个字段排序
 * @Author   CCH
 * @DateTime 2020-05-24T13:14:15+0800
 * @param    $arr        排序数组
 * @param    $field_name 字段名
 * @param    $sort_type  排序方式
 * @return   排序后数组
 */
function arrSortByField($arr, $field_name, $sort_type = SORT_ASC) {
    $fields  = array_column($arr,$field_name);
    array_multisort($fields, $sort_type, $arr);
    return $arr;
}

// xml转数组
function xmlToArray($xml){
    return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}



/**
 * 上传文件
 * @Author   CCH
 * @DateTime 2020-05-23T12:20:41+0800
 * @param    file   file文件对象
 * @return   上传结果
 */
// function uploadFile($file_name,$tmp_name,$path=''){
//     try{
//         $config = config('config.aliyun_oss');
//         $object = $path.uuidCreate().'.'.pathinfo($file_name,PATHINFO_EXTENSION);
//         $oss = new \OSS\OssClient($config['keyId'],$config['keySecret'],$config['endpoint']);
//         $result = $oss->uploadFile($config['bucket'], $object, $tmp_name);
//         return ['status'=>1,'data'=>$object];
//     } catch(OssException $e) {
//         return ['status'=>0,'msg'=>$e->getMessage()];
//     }
//     return true;
// }
// function uploadFile($file_name,$tmp_name,$path=''){
//     try{
//         $file = request()->file('file');
//         $info = $file->move('./uploads');
//         if(!$info){
//             return ['status'=>0,'msg'=>'fail'];
//         }
//         return ['status'=>1,'data'=>str_replace('\\', '/', $info->getSaveName())];
//     } catch(OssException $e) {
//         return ['status'=>0,'msg'=>$e->getMessage()];
//     }
//     return true;
// }

/**
 * CURL请求
 * @Author   CCH
 * @DateTime 2020-06-07T17:14:32+0800
 * @param    $url [description]
 * @param string $data [description]
 * @param string $method [description]
 * @return           [description]
 */
function httpRequest($url, $data = '', $method = 'GET',$header=[])
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    if(strpos($url,'https') !==false){
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); // 对认证证书来源的检查
    }
    // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    // curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    if ($method == 'POST') {
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        if ($data != '') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    }
    if (!empty($header)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }

    curl_setopt($curl, CURLOPT_TIMEOUT, 180);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}


function xml_data($url,$xmlData,$timeout=20){
    $header = array();
    $header[] = "Content-type: text/xml";      //定义content-type为xml,注意是数组
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

//导出csv格式
// function downloadFile( $file_path  ) {
//     $excel = new \PHPExcel();
//     $excel_sheet = $excel->getActiveSheet();
//     $excel_sheet->fromArray($data);
//     $excel_writer = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');

//     $file_name = '用户数据.xlsx';
//     $file_path = './excel/'.$file_name;
//     $excel_writer->save($file_path);
//     if (!file_exists($file_path)) {
//         throw new \Exception("Excel生成失败");
//     }

//     $paths = explode('/', $file_path);
//     $contents = file_get_contents($file_path);
//     $file_size = filesize($file_path);
//     header("Content-type: application/octet-stream;charset=utf-8");
//     header("Accept-Ranges: bytes");
//     header("Accept-Length: $file_size");
//     header("Content-Disposition: attachment; filename=".$paths[count($paths)-1]);
//     echo $contents;
// }
// 下载excel
function downloadFile( $file_name , $data  ) {
    try{
        $excel = new \PHPExcel();
        $excel_sheet = $excel->getActiveSheet();
        $excel_sheet->fromArray($data);
        $excel_writer = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');

        $file_path = './excel/'.$file_name;
        $excel_writer->save($file_path);
        if (!file_exists($file_path)) {
            throw new \Exception("Excel生成失败");
        }

        $paths = explode('/', $file_path);
        $contents = file_get_contents($file_path);
        $file_size = filesize($file_path);
        header("Content-type: application/octet-stream;charset=utf-8");
        header("Accept-Ranges: bytes");
        header("Accept-Length: $file_size");
        header("Content-Disposition: attachment; filename=".$file_name);
        echo $contents;
        exit();
    } catch (\Exception $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }
}

// function writeLog($type,$content=''){
//     $space = "    ";
//     switch ($type) {
//         case 'order':
//             $dirpath = './logs/'.date("Ymd",time());
//             if (!is_dir($dirpath)) { mkdir($dirpath); }
//             $filename = $dirpath.'/'.date('H').'.txt';

//             $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
//             $result = file_put_contents($filename, $filecontent,FILE_APPEND);
//             break;
//         case 'search':
//             $dirpath = './logs/search';
//             // if (!is_dir($dirpath)) { mkdir($dirpath); }
//             $filename = $dirpath.'/'.date("Ymd").'.txt';

//             $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
//             $result = file_put_contents($filename, $filecontent,FILE_APPEND);
//             break;
//         case 'error':
//             $dirpath = './logs/error';
//             // if (!is_dir($dirpath)) { mkdir($dirpath); }
//             $filename = $dirpath.'/'.date("Ymd").'.txt';

//             $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
//             $result = file_put_contents($filename, $filecontent,FILE_APPEND);
//             break;
//         default: break;
//     }
//     return $result;
// }
function writeLog($type,$content=''){
    $space = "    ";
    $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
    $api_url = config('config.system.logs_url');
    $result = post_data($api_url,['type'=>$type,'content'=>$filecontent],1);
    return ture;
}

/**
 * 统一api返回函数
 * @Author   CCH
 * @DateTime 2020-05-23T12:19:19+0800
 * @param    code   结果编码
 * @param    msg    说明
 * @param    data   数据
 * @return   统一格式返回json
 */
function apiResult($code,$msg='',$data=null){
    $result = ['code'=>$code];
    !empty($msg) && $result['msg'] = $msg;
    if ( !is_null($data) ) {
      is_object($data) && $data = $data->toarray();
      if ( isset($data['data']) ) {
        $result['result'] = $data;
      }else{
        $result['result'] = array();
        $result['result']['data'] = $data;  
      }
    }
    return json($result);
}

function searchResult($result){
    try {
        $content = json_encode(request()->param())."，结果：".json_encode($result,JSON_UNESCAPED_UNICODE);
        writeLog('search',$content);
    } catch (\Exception $e) { }
    return json($result);
}

// 获取手机归属地 - 淘宝，部分号码运营商有误
function getMobileInfo($mobile){ 
    $res = array('province'=>'', 'catname'=>'');    //初始化变量 
    $url = 'http://cx.shouji.360.cn/phonearea.php?number='.$mobile;
    $result = @file_get_contents($url);
    $result = json_decode($result,true);
    if($result['code'] == '0'){
        $res['province'] = $result['data']['province'];
        if ($res['province'] == '海南省') {
            $res['province'] = '海南';
        }elseif ($res['province'] == '吉林省') {
            $res['province'] = '吉林';
        }
        $res['city'] = $result['data']['city'];
        $res['catname'] = $result['data']['sp'];
        switch ($res['catname']) {
            case '移动': $res['type'] = 'ChinaMobile'; break;
            case '电信': $res['type'] = 'ChinaTelecom'; break;
            case '联通': $res['type'] = 'ChinaUnicom'; break;
        }
    }
    return $res; 
}

function getProvinceList(){
    $province_list = array('江苏'=>'江苏','辽宁'=>'辽宁','福建'=>'福建','湖北'=>'湖北','广东'=>'广东','北京'=>'北京','上海'=>'上海','陕西'=>'陕西','云南'=>'云南','湖南'=>'湖南','河北'=>'河北','四川'=>'四川','山东'=>'山东','重庆'=>'重庆','黑龙江'=>'黑龙江','江西'=>'江西','新疆'=>'新疆','海南'=>'海南','浙江'=>'浙江','天津'=>'天津','山西'=>'山西','河南'=>'河南','广西'=>'广西','吉林'=>'吉林','甘肃'=>'甘肃','贵州'=>'贵州','内蒙古'=>'内蒙古','安徽'=>'安徽','西藏'=>'西藏','宁夏'=>'宁夏','青海'=>'青海','台湾省'=>'台湾省','香港特别行政区'=>'香港特别行政区','澳门特别行政区'=>'澳门特别行政区');
    return $province_list;
}

function my_build_query($data,$is_retain=0){
    $str = '';
    foreach ($data as $k => $v) {
        $str .= $k.'='.$v.'&';
    }
    if ($str != '' && $is_retain == 0) {
        $str = substr($str,0,strlen($str)-1);
    }
    return $str;
}


/**
 * 上传文件
 * @Author   CCH
 * @DateTime 2020-05-23T12:20:41+0800
 * @param    file   file文件对象
 * @return   上传结果
 */
function uploadOss($file_name,$tmp_name,$path=''){
    try{
        $config = config('config.aliyun_oss');
        $object = $path.uuidCreate().'.'.pathinfo($file_name,PATHINFO_EXTENSION);
        $oss = new \OSS\OssClient($config['keyId'],$config['keySecret'],$config['endpoint']);
        $result = $oss->uploadFile($config['bucket'], $object, $tmp_name);
        return ['status'=>1,'data'=>$object];
    } catch(OssException $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }catch (\Exception $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }
    return true;
}

/**
 * 上传文件
 * @Author   CCH
 * @DateTime 2020-05-23T12:20:41+0800
 * @param    file   file文件对象
 * @return   上传结果
 */
function downloadOss($object,$localfile=''){
    try{
        $config = config('config.aliyun_oss');
        if ( empty($localfile) ) {
            $localfile = $config['localpath'].$object;
        }
        $oss = new \OSS\OssClient($config['keyId'],$config['keySecret'],$config['endpoint']);
        // dump($oss);
        // 判断文件是否存在
        if ( !$oss->doesObjectExist($config['bucket'], $object) ) { 
            throw new \Exception("文件不存在");
        }
        $objectMeta = $oss->getObjectMeta($config['bucket'], $object);
        // dump($objectMeta);
        $file_type = '';
        switch ($objectMeta['content-type']) {
            case 'application/x-zip-compressed': $file_type = 'zip'; break;
            case 'application/csv': $file_type = 'csv'; break;
        }
        if (empty($file_type)) {
            throw new \Exception("无法获取文件类型");  
        }
        $localfile = $localfile.'.'.$file_type;
        $result = $oss->getObject($config['bucket'], $object, [
            \OSS\OssClient::OSS_FILE_DOWNLOAD => $localfile
        ]);
        // dump($result);
        return ['status'=>1,'data'=>$object,'type'=>$file_type];
    } catch(OssException $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }catch (\Exception $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }
    return true;
}


function exportCsv($title, $headArr, $exportData) {
    $total = count($exportData);
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:filename=" . iconv("UTF-8", "GB18030", $title) . ".csv");
    $fp = fopen('php://output', 'a');
    fputcsv($fp, $headArr);
    $size = 2000;
    $groupNum = ceil($total / $size);
    for ($i = 0; $i <= $groupNum; $i++) {
        $exportDataTemp = array_slice($exportData, $size * $i, $size);
        foreach ($exportDataTemp as $item) {
            // $rows = array();
            // foreach ($headName as $name) {
            //     $rows[] = $item[$name];
            // }
            // die;
            // fputcsv($fp, $rows);
            fputcsv($fp, $item);
        }
        ob_flush();
        flush();
    }
    die;
}

function exportReplace($str){
    return str_replace([",","\"","\r\n"],["，","'","；"],$str);
}

function sendSms($mobile,$content,$sign='融合云'){
    if (empty($mobile) || empty($content)) {
        return false;
    }
    if (!empty($sign)) {
        $content = '【'.$sign.'】'.$content;
    }
    $api_url = 'http://47.97.215.253:8001/sms/api/sendMessage';
    $params = [
        'userName'=>'广州骉云',
        'content'=>$content,
        'phoneList'=>[$mobile],
        'timestamp'=>time().'000',
    ];
    $params['sign'] = md5($params['userName'].$params['content'].$params['timestamp'].md5('123456'));
    $api_res = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
        'Content-Type: application/json'
    ]);
    $api_res = json_decode($api_res,true);
    if ($api_res['code'] == '0') {
        return ['status'=>1];
    }else{
        return ['status'=>0,'msg'=>$api_res['message']];
    }
}

function showColorSpan($str,$key,$colors=1){
    if ( $colors == 1 ) {
        $colors = ['danger','success'];
    }elseif ( $colors == 2 ) {
        $colors = ['default','success',-1=>'danger'];
    }
    $color = empty($colors[$key])?'default':$colors[$key];
    return '<span class="label label-'.$color.'">'.$str.'</span>';
}

function cchtest($content=''){
    Db::name('test')->insert(['content'=>$content]);
}

function adminRoleMap(&$map){
    // if (!adminCheck()) {
    //     $login_user = session("cch_admin");
    //     $map[] = ['admin_id','=',$login_user['id']];
    // }
    return true;
}

function adminCheck($roles=['0']){
    $login_user = session("cch_admin");
    if (in_array($login_user['role'], $roles)) {
        return true;
    }else{
        return false;
    }
}

function apiSuccessResult($msg,$data=[]){
    $result = ['status'=>1,'msg'=>$msg];
    if (!empty($data)) {
        $result['data'] = $data;
    }
    return $result;
}

function apiErrorResult($msg,$data=[]){
    $result = ['status'=>0,'msg'=>$msg];
    if (!empty($data)) {
        $result['data'] = $data;
    }
    return $result;
}

/*
+----------------------------------------------------------
 * 功能：删除某个文件夹下所有的文件夹和文件
+----------------------------------------------------------
 * @param string    $dir      要删除的文件夹的路径
+----------------------------------------------------------
 */
function del_dir($dir) {
    if (!is_dir($dir)) {
        return false;
    }
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        if ($file != "." && $file != "..") {
            is_dir($dir."/$file") ? del_dir($dir."/$file") : @unlink($dir."/$file");
        }
    }
    if (readdir($handle) == false) {
        closedir($handle);
        @rmdir($dir);
    }
    return true;
}

function createPageSort($field_name,$default_field='id',$default_type='desc'){
    $params = request()->param();
    $order_field = $params['order_field'];
    if (empty($order_field)) {
        $order_field = $default_field;
    }
    $order_type = $params['order_type'];
    if (empty($order_type)) {
        $order_type = $default_type;
    }
    $view_content = [
        '<div class="sort_div">'
    ];

    $url = request()->controller().'/'.request()->action();
    if ( !($order_field == $field_name && $order_type == 'asc') ) {
        $params['order_field'] = $field_name;
        $params['order_type'] = 'asc';
        $view_content[] = '<a href="'.url($url,$params).'"><i class="mdi mdi-chevron-up"></i></a>';
    }

    if ( !($order_field == $field_name && $order_type == 'desc') ) {
        $params['order_field'] = $field_name;
        $params['order_type'] = 'desc';
        $view_content[] = '<a href="'.url($url,$params).'"><i class="mdi mdi-chevron-down"></i></a>';
    }
    $view_content[] = '</div>';

    echo implode('', $view_content);
}

function diffDays($time1='',$time2=''){
    if (empty($time1)) {
        return '';
    }
    if (empty($time2)) {
        $time2 = time();
    }
    if ($time1 < $time2) {
        return '已过期';
    }
    $diff_seconds = $time1 - $time2;
    $diff_days = floor($diff_seconds / 86400);
    $diff_hour = floor($diff_seconds % 86400 / 3600);

    $content = '';
    if (!empty($diff_days)) {
        $content = $content.$diff_days.'天';
    }
    if (!empty($diff_hour)) {
        $content = $content.$diff_hour.'小时';
    }

    return $content;
}

// 判断是否手机号
function isMobile($mobile){
    if ( !preg_match("/^1\d{10}$/",$mobile)  ) {
        return false;
    }
    return true;
}

// 判断是否邮箱
function isEmail($email){
    if ( !preg_match('/^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/',$email) ) {
        return false;
    }
    return true;
}

// 删除数组空元素
function delArrEmpty($arr=[]){
    foreach ($arr as $k => $vo) {
        if (empty($vo)) {
            unset($arr[$k]);
        }
    }
    return $arr;
}

// 验证域名格式
function checkUrl($c_url){  
    $str="/^([a-zA-Z0-9])+\.([a-zA-Z0-9_-])+(\.[a-zA-Z0-9])+/";  
    if (!preg_match($str,$c_url)){  
        return false;  
    }else{  
        return true;  
    }  
}

/**
 * RSA数据加密解密
 * @param type $data
 * @param type $type encode加密  decode解密
 */
function RSA_openssl($data,$type='encode'){
    if (empty($data)) {
        return 'data参数不能为空';
    }
    if (is_array($data)) {
        return 'data参数不能是数组形式';
    }
 
    $rsa_public = config('rsa_public');
    if(empty($rsa_public)){
        $pubKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXQEIX46LEg0jKaA27yeW4x9CoGu9zc3ZNLd4MApjjfQkQSVO4nyOh0otCa933fjlzry1nNcYwA8pRJauu2IB_2d_DPLUaqw_ywthnbYNzYoiltGqS_c6-LVWRbflcdVia7kNnT-7A2sMpyBAO4lmFyW67b_Hisl_S83Bkty31lQIDAQAB';
        $str  = chunk_split($pubKey, 64, "\n");
        $rsa_public = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
        $rsa_public = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDC9kMNVuFE+2qnb1vXjlRmjKhd
HR0AEe3i/p0iQNwB082raTulbM2NNdlstG+otWweScbfxwdIj2zylVm31kdEt5yp
wOD4rzDq8MEK51R9wXLzPxPAbJK48occlTdfuh6hX2nK11Toe4D0GaMsE++SanE5
6/d49uXc/ZOrQeAk3QIDAQAB
-----END PUBLIC KEY-----';
        dump($rsa_public);
    }
    $rsa_private = config('rsa_private');
    if(empty($rsa_private)){
        $rsa_private = '-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKaQA2YLzj0g6e1h
BB1KAu8wwabxX+7zfwBMdqhnC/B6hjJ37/tbH5vHlt2S0lvjphupLW/PdVF1ezIk
haGk1ya0qFiKfByXzdou3Ml4qzOemmozIAix5ooh4Cbq1Py6202SvbM7KYv89syk
HJNB4QWXLLWmgsHCuiXQXhRJz6jDAgMBAAECgYAIF5cSriAm+CJlVgFNKvtZg5Tk
93UhttLEwPJC3D7IQCuk6A7Qt2yhtOCvgyKVNEotrdp3RCz++CY0GXIkmE2bj7i0
fv5vT3kWvO9nImGhTBH6QlFDxc9+p3ukwsonnCshkSV9gmH5NB/yFoH1m8tck2Gm
BXDj+bBGUoKGWtQ7gQJBANR/jd5ZKf6unLsgpFUS/kNBgUa+EhVg2tfr9OMioWDv
MSqzG/sARQ2AbO00ytpkbAKxxKkObPYsn47MWsf5970CQQDIqRiGmCY5QDAaejW4
HbOcsSovoxTqu1scGc3Qd6GYvLHujKDoubZdXCVOYQUMEnCD5j7kdNxPbVzdzXll
9+p/AkEAu/34iXwCbgEWQWp4V5dNAD0kXGxs3SLpmNpztLn/YR1bNvZry5wKew5h
z1zEFX+AGsYgQJu1g/goVJGvwnj/VQJAOe6f9xPsTTEb8jkAU2S323BG1rQFsPNg
jY9hnWM8k2U/FbkiJ66eWPvmhWd7Vo3oUBxkYf7fMEtJuXu+JdNarwJAAwJK0YmO
LxP4U+gTrj7y/j/feArDqBukSngcDFnAKu1hsc68FJ/vT5iOC6S7YpRJkp8egj5o
pCcWaTO3GgC5Kg==
-----END PRIVATE KEY-----';
    }
 
    //私钥解密
    if ($type=='decode') {
        $private_key = openssl_pkey_get_private($rsa_private);
        if (!$private_key) {
            return('私钥不可用');
        }
        $return_de = openssl_private_decrypt(base64_decode($data), $decrypted, $private_key);
        if (!$return_de) {
            return('解密失败,请检查RSA秘钥');
        }
        return $decrypted;
    }
 
    //公钥加密
    $key = openssl_pkey_get_public($rsa_public);
    if (!$key) {
        return('公钥不可用');
    }
    //openssl_public_encrypt 第一个参数只能是string
    //openssl_public_encrypt 第二个参数是处理后的数据
    //openssl_public_encrypt 第三个参数是openssl_pkey_get_public返回的资源类型
    $return_en = openssl_public_encrypt($data, $crypted, $key);
    if (!$return_en) {
        return('加密失败,请检查RSA秘钥');
    }
    return base64_encode($crypted);
}


// 日期转成大写
function toDateChineseV2($date) {
    $date_arr = explode('-', $date);
    $year = $date_arr[0];
    $month = (int)$date_arr[1];
    $day = (int)$date_arr[2];
    $numToUpper = [
        0 => '〇', 1 => '一', 2 => '二', 3 => '三', 4 => '四',
        5 => '五', 6 => '六', 7 => '七', 8 => '八', 9 => '九',
        10 => '十', 11 => '十一', 12 => '十二', 13 => '十三', 14 => '十四',
        15 => '十五', 16 => '十六', 17 => '十七', 18 => '十八', 19 => '十九',
        20 => '二十', 21 => '二十一', 22 => '二十二', 23 => '二十三', 24 => '二十四',
        25 => '二十五', 26 => '二十六', 27 => '二十七', 28 => '二十八', 29 => '二十九',
        30 => '三十', 31 => '三十一'
    ];
    $srt = '';
    $yearArr = str_split($year);

    foreach ($yearArr as $v) {
        $srt .= $numToUpper[$v];
    }
    $srt .= '年';
    $srt .= $numToUpper[$month] . '月';
    $srt .= $numToUpper[$day] . '日';
    return $srt;
}

/**
 * 将数值金额转换为中文大写金额
 * @param $amount float 金额(支持到分)
 * @param $type   int   补整类型,0:到角补整;1:到元补整
 * @return mixed 中文大写金额
 */
function convertAmountToCn($amount, $type = 0)
{
    // 判断输出的金额是否为数字或数字字符串
    if (!is_numeric($amount)) {
        return "要转换的金额只能为数字!";
    }

    // 金额为0,则直接输出"零元整"
    if ($amount == 0) {
        return "零";
    }

    // 金额不能为负数
    if ($amount < 0) {
        return "要转换的金额不能为负数!";
    }
    // 将金额的数值字符串拆分成数组
    $amountArr = explode('.', $amount);
    if (count($amountArr) > 1) {
        if (strlen($amountArr[1] >= 3)) {
            return '要转换的金额最小为分';
        }
    }

    // 金额不能超过万亿,即12位
    if (strlen($amount) > 12) {
        return "要转换的金额不能为万亿及更高金额!";
    }

    // 预定义中文转换的数组
    $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    // 预定义单位转换的数组
    $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '');
    // $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');


    // 将整数位的数值字符串拆分成数组
    $integerArr = str_split($amountArr[0], 1);

    // 将整数部分替换成大写汉字
    $result = '';
    $integerArrLength = count($integerArr);     // 整数位数组的长度
    $positionLength = count($position);         // 单位数组的长度
    for ($i = 0; $i < $integerArrLength; $i++) {
        // 如果数值不为0,则正常转换
        if ($integerArr[$i] != 0) {
            $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
        } else {
            // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
            if (($positionLength - $integerArrLength + $i + 1) % 4 == 0) {
                $result = $result . $position[$positionLength - $integerArrLength + $i];
            }
        }
    }

    // 如果小数位也要转换
    if ($type == 0) {
        // 将小数位的数值字符串拆分成数组
        if (count($amountArr) > 1) {
            $decimalArr = str_split($amountArr[1], 1);
            // 将角替换成大写汉字. 如果为0,则不替换
            if ($decimalArr[0] != 0) {
                // $result = $result . $digital[$decimalArr[0]] . '角';
                $result = $result .'.'. $digital[$decimalArr[0]];
            }
            if (count($decimalArr) > 1) {
                // 将分替换成大写汉字. 如果为0,则不替换
                if ($decimalArr[1] != 0) {
                    // $result = $result . $digital[$decimalArr[1]] . '分';
                    $result = $result . $digital[$decimalArr[1]];
                }
            }

        }
    } else {
        $result = $result . '整';
    }
    return $result;
}


function toChineseNumber($money){
  $money = round($money,2);
  $cnynums = array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"); 
  $cnyunits = array("圆","角","分");
  $cnygrees = array("拾","佰","仟","万","拾","佰","仟","亿"); 
  list($int,$dec) = explode(".",$money,2);
  $dec = array_filter(array($dec[1],$dec[0])); 
  $ret = array_merge($dec,array(implode("",cnyMapUnit(str_split($int),$cnygrees)),"")); 
  $ret = implode("",array_reverse(cnyMapUnit($ret,$cnyunits))); 
  return str_replace(array_keys($cnynums),$cnynums,$ret); 
}
function cnyMapUnit($list,$units) { 
  $ul=count($units); 
  $xs=array(); 
  foreach (array_reverse($list) as $x) { 
    $l=count($xs); 
    if ($x!="0" || !($l%4)) 
      $n=($x=='0'?'':$x).($units[($l-1)%$ul]); 
    else $n=is_numeric($xs[0][0])?$x:''; 
 array_unshift($xs,$n); 
 } 
 return $xs; 
 }

 function convert_number_to_rmb($number) {
    $units = array('分', '角', '元', '十', '百', '千', '万', '十万', '百万', '千万', '亿', '十亿', '百亿', '千亿');
    $digit = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    $num_units = count($units);
    $num_digit = count($digit);
    // 将数字按小数点分割成整数部分和小数部分
    $number_array = explode('.', $number);
    // 将整数部分拆分成数组
    $int_array = str_split($number_array[0]);
    // 初始化结果
    $result = '';
    // 添加元和整数部分的大写
    for ($i = 0; $i < count($int_array); $i++) {
        $unit_key = ($num_units - 1) - ((count($int_array) - 1 - $i) % $num_units);
        $digit_key = $int_array[$i];
        $result .= $digit[$digit_key] . $units[$unit_key];
    }
    // 如果有小数部分，添加小数部分的大写
    if (count($number_array) == 2) {
        $fraction_array = str_split($number_array[1]);
        for ($i = 0; $i < count($fraction_array); $i++) {
            $unit_key = $num_units - 3 + $i;
            $digit_key = $fraction_array[$i];
            if ($digit_key == 0 && $i == 0) {
                $result .= '整';
                break;
            }
            $result .= $digit[$digit_key] . $units[$unit_key];
        }
    } else {
        $result .= '整';
    }
    return $result;
}

// 权限
function roleCheck($roles = []){
    $ulogin = session("cch_admin");
    $roles[] = 'admin';
    $is_have = array_intersect(explode(',',$ulogin['role']), $roles);
    if (!empty($is_have)) {
        return true;
    }else{
        return false;
    }
}

/**
 * 获取微信操作对象（单例模式）
 * @staticvar array $wechat 静态对象缓存对象
 * @param type $type 接口名称 ( Card|Custom|Device|Extend|Media|Oauth|Pay|Receive|Script|User ) 
 * @return \Wehcat\WechatReceive 返回接口对接
 */
function & load_wechat($type = '') {
    static $wechat = array();
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {
        // 定义微信公众号配置参数（这里是可以从数据库读取的哦）
       $options = array(
            'token'           => 'weiphp', // 填写你设定的key
            'appid'           => 'wx2626e5159782ebbb', // 填写高级调用功能的app id, 请在微信开发模式后台查询
            'appsecret'       => 'a43952f7454b441c7de233dbb5034c62', // 填写高级调用功能的密钥
            'encodingaeskey'  => '', // 填写加密用的EncodingAESKey（可选，接口传输选择加密时必需）
            'mch_id'          => '', // 微信支付，商户ID（可选）
            'partnerkey'      => '', // 微信支付，密钥（可选）
            'ssl_cer'         => '', // 微信支付，双向证书（可选，操作退款或打款时必需）
            'ssl_key'         => '', // 微信支付，双向证书（可选，操作退款或打款时必需）
            'cachepath'       => '', // 设置SDK缓存目录（可选，默认位置在Wechat/Cache下，请保证写权限）
        );
        \Wechat\Loader::config($options);
        $wechat[$index] = \Wechat\Loader::get($type);
    }
    return $wechat[$index];
}

function sendTemplateMessage($openid,$template_id,$data=[],$miniprogram=[],$url=''){
    // $openid = Db::name('user')->where('id',$user_id)->value('gzh_openid');
    if (empty($openid)) {
        return false;
    }
    // if (isset($data['first']) && empty($data['first'])) {
    //     $data['first'] = [
    //         'value'=>Db::name('template_message')->where([
    //             'template_id'=>$template_id,
    //             'field_name'=>'first'
    //         ])->value('content')
    //     ];
    // }
    // if (isset($data['remark']) && empty($data['remark'])) {
    //     $data['remark'] = [
    //         'value'=>Db::name('template_message')->where([
    //             'template_id'=>$template_id,
    //             'field_name'=>'remark'
    //         ])->value('content')
    //     ];
    // }
    $wechat = &load_wechat('Receive');
    $data = [
        'touser'=>$openid,
        'template_id'=>$template_id,
        'url'=>$url,
        'miniprogram'=>$miniprogram,
        'data'=>$data
    ];
    $result = $wechat->sendTemplateMessage($data);
    return $result;
}